package vn.com.fsoft.model.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import vn.com.fsoft.model.dao.IReferenceDataDao;
import vn.com.fsoft.model.entities.ReferenceData;
import vn.com.fsoft.utility.HibernateUtils;

public class ReferenceDataDao extends HibernateUtils implements IReferenceDataDao{
	
	private Session session;
	private static int totalPage;
	public ReferenceDataDao(){
		if(session==null)
			session = getSessionFactory().openSession();
	}
	
	public List<ReferenceData> lookUpBussiness(String bussinessName, String sicCode,int pageSize,int currentPage) {
		try {
			if(bussinessName == null || sicCode == null) {
				return null;
			} else if(bussinessName.length() > 0){
				bussinessName = "%"+bussinessName.toLowerCase()+"%";				
				session.getTransaction().begin();
				String sql = "from ReferenceData as r "
				+" where lower(r.refValue) like :bName";
				if(sicCode.length()>0){
					sql+=" or lower(r.refCode) like :sicCode";
				}
				Query query = session.createQuery(sql);
				query.setParameter("bName", bussinessName);
				if(sicCode.length()>0){
					sicCode = "%"+sicCode.toLowerCase()+"%";
					query.setParameter("sicCode", sicCode);
				}				
				int totalRecord = query.list().size();		
				setTotalPage(totalRecord,pageSize);
				query.setFirstResult(pageSize * (currentPage - 1));
				query.setMaxResults(pageSize);
				List<ReferenceData> list = query.list();				
				session.flush();
				session.getTransaction().commit();
				return list;
			}
			return null;
		} catch (Exception e) {			
			session.getTransaction().rollback();		
		}
		return null;
	}	
	
	@Override
	public int getTotalPage() {		
		return totalPage;
	}
	public void setTotalPage(int totalRecord,int pageSize) {
		int totalPage = 0;
		if(totalRecord%pageSize==0){
			totalPage = totalRecord/pageSize;
		} else {
			totalPage = totalRecord/pageSize + 1;
		}
		ReferenceDataDao.totalPage = totalPage;
	}	
}
